package com.mar.meclient.bt.impl;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.Display;

import net.java.dev.marge.communication.CommunicationListener;

import com.mar.meclient.bt.BTMidlet;
import com.mar.meclient.util.ByteBuffer;
import com.mar.meclient.util.Queue;
import com.mar.meclient.util.SyncBlockingQueue;
/**
 * TODO: implement carefully exception handling!
 * @author mar
 *
 */
class BTInputStream extends InputStream implements CommunicationListener {
	
	Queue syncQueue = new SyncBlockingQueue(200);

	public BTInputStream()  {
	}
	
	private ByteBuffer buffer = null;
	
	public int read() throws IOException {
		if ( buffer == null || !buffer.hasRemaining() ){// no buffer available or buffer is read
			buffer = (ByteBuffer) syncQueue.pop();
		}
		return buffer.get();
	}
	
	public void errorOnReceiving(IOException arg0) {
		// TODO Auto-generated method stub
		
	}

	public void errorOnSending(IOException arg0) {
		// TODO Auto-generated method stub
		
	}

	public void receiveMessage(byte[] message) {
		//TODO: log
		counter += message.length;
		Display.getDisplay( BTMidlet.getInstance() ).getCurrent().setTitle(String.valueOf(counter) );
		syncQueue.push( ByteBuffer.wrap(message) );
	}
	static int counter = 0;
}
